package com.texplose.job;

import com.texplose.entity.Recipe;
import com.texplose.entity.constant.SystemConstants;
import com.texplose.service.RecipeService;
import com.texplose.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : lyj
 * @Timer : 2022/5/24
 * @Description :
 */
@Component
public class UpdateViewJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RecipeService recipeService;

    // @Scheduled(cron = "*/5 * * * * ?") 五秒执行一次
    // 0 */10 * * * ? 十分钟执行一次
    @Scheduled(cron = "0 */10 * * * ?")
    public void updateView() {
        Map<String, Integer> viewMap = redisCache.getCacheMap(SystemConstants.REDIS__VIEWS_MAP);

        //从redis中获取id和view
        List<Recipe> recipeList = viewMap.entrySet()
                .stream()
                .map(entry -> new Recipe(Integer.valueOf(entry.getKey()), entry.getValue()))
                .collect(Collectors.toList());
        //批量更新数据库中数据
        for (Recipe recipe : recipeList) {
            recipeService.updateViewById(recipe.getId(),recipe.getViews());
        }


    }

}
